const http = require('http');
const axios = require('axios');

const clients = [];

const server = http.createServer((req, res) => {
  if (req.url === '/subscribe') {
    let body = '';

    req.on('data', (chunk) => {
      body += chunk.toString();
    });

    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      Connection: 'keep-alive',
    });

    clients.push(res);
    req.on('end', () => {
      try {
        const jsonData = JSON.parse(body);
        console.log(jsonData); // { name: 'John', age: 30 }
        callOllamaApi(jsonData.content, res);
      } catch (error) {
        res.writeHead(400, { 'Content-Type': 'text/plain' });
        res.end('Invalid JSON');
      }
    });
    req.on('close', () => {
      const index = clients.indexOf(res);
      if (index !== -1) {
        clients.splice(index, 1);
      }
    });
  } else {
    res.writeHead(404);
    res.end();
  }
});

server.listen(3001, () => {
  console.log('SSE server running on http://localhost:3001');
});

async function callOllamaApi(content, res) {
  const url = 'http://0.0.0.0:11434/api/chat';

  try {
    const response = await axios.post(
      url,
      {
        model: 'qwen2:0.5b',
        stream: false,
        temperature: 0.7,
        messages: [
          {
            role: 'user',
            content: content,
          },
        ],
      },
      {
        headers: {
          'Content-Type': 'application/json',
          origin: 'http://0.0.0.0:11434',
        },
      }
    );

    const data = response.data.message.content;
    var index = 0;
    const sendChar = () => {
      if (index < data.length) {
        var char = data[index];
        var enterchar = "";
        if (char === '\n') {
          enterchar = '\\n'; // 发送换行符的转义表示
        } else if (char === '\r') {
          enterchar = '\\r'; // 发送换行符的转义表示
        } else {
          enterchar = `${char}`;
        }
        sendEvent(`event:${index != data.length - 1 ? 'add' : 'finish'}\ndata: ${enterchar}\n\n`);
        index++;
        setTimeout(sendChar, 15); // 每隔15毫秒发送一个字符
      } else {
        res.end(); // 发送完毕后关闭连接
      }
    };
    sendChar();
  } catch (error) {
    console.error('Error calling Ollama API:', error.message);
    if (error.response) {
      console.error('Response data:', error.response.data);
      console.error('Response status:', error.response.status);
    }
  }
}

function sendEvent(data) {
  clients.forEach((client) => {
    client.write(data);
  });
}

//setInterval(callOllamaApi, 5000);
//
